﻿#include "textmessage.h"

TextMessage::TextMessage(const QString &text,QWidget *parent)
    : BaseMessage{parent}
{
    setDefaultOption();
    this->setPlainText(text);
}
TextMessage::TextMessage(const QString &text, const QString &filePath, QWidget *parent)
    : BaseMessage{parent}
    , filePath(filePath)
{
    setDefaultOption();
    this->setPlainText(text);
}

void TextMessage::resizeEvent(QResizeEvent* event){
    QSize newSize = event->size();
    QFontMetricsF fm(this->font());
    double n_str=fm.horizontalAdvance(this->toPlainText())/fm.width(" ");//多少个空格才能占满这个字符串
    double n_line=newSize.width()/fm.width(" ")-2;//多少个空格才能占满一行
    if(n_str-n_line>0.8){//处理多行
        QWidget* oneWidget=this->parentWidget();
        int lineHeight=ceil(n_str/n_line)*fm.lineSpacing()+10;
        oneWidget->setFixedHeight(lineHeight);
        QWidget* twoWidget=oneWidget->parentWidget();
        QWidget* fourWidget=twoWidget->parentWidget()->parentWidget();
        int height=twoWidget->minimumHeight()-40+lineHeight;
        fourWidget->setFixedHeight(increase+40+height);
    }
    else//处理单行
    {
        QWidget* oneWidget=this->parentWidget();
        oneWidget->setFixedHeight(40);
        QWidget* twoWidget=oneWidget->parentWidget();
        QWidget* fourWidget=twoWidget->parentWidget()->parentWidget();
        int height=twoWidget->minimumHeight()-40+40;
        fourWidget->setFixedHeight(increase+40+height);
    }
    QTextEdit::resizeEvent(event);
}
QString TextMessage::getFilePath(){
    return this->filePath;
}

void TextMessage::setDefaultOption(){
    this->setWordWrapMode(QTextOption::WrapAnywhere);
    this->setReadOnly(true);
    this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->setFont(QFont("Microsoft YaHei UI",11));
}
